package com.flushbonading.classsystem.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author zyx 2134208960@qq.com
 * @date 2021/11/10 17:17
 * @since 1.0.0
 */
@Component
@Slf4j
public class GateWayFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (exchange.getRequest().getPath().value().contains("login")){
            return chain.filter(exchange);
        }
        if (!exchange.getRequest().getHeaders().containsKey("token")){
            System.out.println("请求被拦截了");
            exchange.getResponse().setStatusCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION);
            return exchange.getResponse().setComplete();
        }else {
            ServerHttpRequest request = exchange.getRequest().mutate()
                    .headers(httpHeaders -> httpHeaders.remove("from"))
                    .build();
            ServerHttpRequest newRequest = request.mutate().header("from","gateway").build();
            return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
        }
    }
}
